package com.test.dao;

import java.io.Serializable;
import java.util.Map;
import java.util.Map.Entry;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;
import org.springframework.data.repository.NoRepositoryBean;

@NoRepositoryBean
public class IDaoImpl<T, ID extends Serializable> extends SimpleJpaRepository<T, Serializable>
		implements IDao<T, Serializable> {

	@SuppressWarnings("unused")

	private final EntityManager entityManager;

	public IDaoImpl(Class<T> domainClass, EntityManager em) {
		super(domainClass, em);
		this.entityManager = em;
		// TODO Auto-generated constructor stub
	}

	@Override
	public long count(String sql, Map<String, Object> filters) {
		Query query = createNativeQuery(sql, filters, null, -1);
		return ((Number) query.getSingleResult()).intValue();
	}

	private Query createNativeQuery(String sql, Map<String, Object> filters, Pageable pageable, int timeout) {
		Query query = entityManager.createNativeQuery(sql);
		if (filters != null) {
			for (Entry<String, Object> filter : filters.entrySet()) {
				query.setParameter(filter.getKey(), filter.getValue());
			}
		}
		if (pageable != null) {
			query.setFirstResult(pageable.getOffset());
			query.setMaxResults(pageable.getPageSize());
		}
		if (timeout > 0) {
			query.setHint("javax.persistence.query.timeout", timeout);
		}
		return query;
	}

}
